var App = App||{};
App.init = function(){
	App.Project.init();
	App.Week.init();
	App.ProjectLog.init();
};

App.ProjectLog = {};

App.ProjectLog.init = function(){
	var self = this;
	this.today = new Date().toStr();
	
	this.from = $('#fromDate')
			.datepicker({ dateFormat: 'yy-mm-dd', firstDay: 1, changeMonth: true, changeYear: true,
				onClose: function(dateText, inst){ $(this).trigger('dateChange', [ dateText ]); }
			})
			.bind('dateChange', $.proxy(this.Refresh, this));
	this.to = $('#toDate')
			.datepicker({ dateFormat: 'yy-mm-dd', firstDay: 1, changeMonth: true, changeYear: true,
				onClose: function(dateText, inst){ $(this).trigger('dateChange', [ dateText ]); }
			})
			.bind('dateChange', $.proxy(this.Refresh, this));
	
	$('#userSelect').toChecklist();
	
	$('#fromDate').datepicker('setDate', new Date().addDays(-7).toStr());
	$('#toDate').datepicker('setDate', new Date().toStr());

	$('#projectPlaceholder').delegate('.project .remove-project', 'click', function(){ self.removeProject.call(self, $(this).closest('.project')); });

	$('#btnRefresh').button({ icons: { primary: 'ui-icon-refresh'} }).bind('click', $.proxy(this.Refresh, this));

	$('#userSelect').delegate('.checklist :checkbox', 'change', this.Refresh);
	
	this.initDrop();
	this.Refresh();
};


App.ProjectLog.Refresh = function(){ App.Week.load(); };
App.ProjectLog.initDrop = function(){ $('#projectPlaceholder').droppable('destroy').droppable({ accept: ".project", activeClass: "drop-ready", hoverClass: "drop-hover", drop: $.proxy(this.projectDrop, this) }); };
App.ProjectLog.removeProject = function(el){
	var self = this;
	el.fadeOut('fast', function(){ 
		$(this).data('projectId','0').html('drop project here').addClass('empty').fadeIn();
		self.Refresh();
	}); 
};


/**
 * Project is dropped on a day
 */
App.ProjectLog.projectDrop = function(ev, ui){
	var project = ui.draggable, projectId = project.data('projectId'), projectName = project[0].childNodes[1].textContent; 
	$(ev.target)
		.html('<div class="project" data-project-id="'+projectId+'"><div class="remove-project"></div>'+projectName+'</div>')
		.css('background','#95BDD4')
		.effect('pulsate', {times:1}, 400, function(){ $(this).css('background',''); });	
	this.initDrop();
	this.Refresh();
};